package cn.wolfcode.orderserver.service.impl;

import cn.wolfcode.orderserver.domain.Order;
import cn.wolfcode.orderserver.feign.ProductFeignApi;
import cn.wolfcode.orderserver.repository.OrderRepository;
import cn.wolfcode.orderserver.service.IOrderService;
import cn.wolfcode.productserver.domain.Product;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @author JMJ
 * @date 2021/3/22 18:56
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderRepository orderRepository;
/*    @Autowired
    private RestTemplate template;
    @Autowired
    private DiscoveryClient discoveryClient;*/

    @Autowired
    private ProductFeignApi productFeignApi;


    @Override
    public Order createOrder(Long uid, Long pid) {
        log.info("接受下{}号商品下单请求 , 查询此商品信息", pid);

        //从nacos中获取服务地址
        //List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
/*        //自定义规则实现随机挑选
        int index = new Random().nextInt(instances.size());

        ServiceInstance instance = instances.get(index);
        String url = instance.getHost() + ":" + instance.getPort();
        log.info("地址为{}",url);
        Product product = template.getForObject("http://" + url + "/product?pid=" + pid, Product.class);*/

        //基于nacos中的robbin实现负载均衡 , 在容器中加入RestTemplate 的时候贴上注解 @LoadBalanced 便能够实现
        //Product product = template.getForObject("http://product-service/product?pid=" + pid, Product.class);


        //远程调用接口 , 自己写接口 , 然后框架帮我们动态代理生成接口实现类去做事
        //并且根据接口上的注解内容去调用接口
        Product product = productFeignApi.findByPid(pid);

        Order order = new Order();
        order.setNumber(1);
        order.setUid(uid);
        order.setUsername("乌蝇");

        //商品
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        orderRepository.save(order);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;
    }
}
